package main

import (
    "encoding/json"

    "chainmaker.org/chainmaker/contract-sdk-go/v2/pb/protogo"
    "chainmaker.org/chainmaker/contract-sdk-go/v2/sandbox"
    "chainmaker.org/chainmaker/contract-sdk-go/v2/sdk"
)

// 主合约结构
type ESGTestContract struct{}

// ESG指标结构
type ESGIndicator struct {
    IndicatorID       string  `json:"indicatorid"`
    IndicatorName     string  `json:"indicatorname"`
    IndicatorContent  string  `json:"indicatorcontent"`
    IndicatorDesc     string  `json:"indicatordescription"`
    Amount            float64 `json:"amount"`
    Unit              string  `json:"unit"`
}

// 合约初始化
func (c *ESGTestContract) InitContract() protogo.Response {
    return sdk.Success([]byte("ESGTestContract Initialized"))
}

// 合约升级
func (c *ESGTestContract) UpgradeContract() protogo.Response {
    return sdk.Success([]byte("ESGTestContract Upgraded"))
}

// 合约入口
func (c *ESGTestContract) InvokeContract(method string) protogo.Response {
    switch method {
    case "save":
        return c.save()
    case "findById":
        return c.findById()
    default:
        return sdk.Error("invalid method: " + method)
    }
}

// 保存 ESG 指标（逐条保存）
func (c *ESGTestContract) save() protogo.Response {
    args := sdk.Instance.GetArgs()

    var payload struct {
        RawData []struct {
            BizIndex string       `json:"bizIndex"`
            BizData  ESGIndicator `json:"bizData"`
        } `json:"rawData"`
    }

    if err := json.Unmarshal(args["data"], &payload); err != nil {
        return sdk.Error("invalid json in data: " + err.Error())
    }

    if len(payload.RawData) == 0 {
        return sdk.Error("rawData is empty")
    }

    for _, item := range payload.RawData {
        indicator := item.BizData
        if indicator.IndicatorID == "" {
            return sdk.Error("indicatorid is required in rawData item")
        }

        bytes, err := json.Marshal(indicator)
        if err != nil {
            return sdk.Error("marshal error: " + err.Error())
        }

        key := indicator.IndicatorID
        if err := sdk.Instance.PutStateByte("ESGindicator", key, bytes); err != nil {
            return sdk.Error("put state failed at key " + key + ": " + err.Error())
        }
    }

    return sdk.Success([]byte("save success"))
}

// 查询 ESG 指标（精简参数结构）
func (c *ESGTestContract) findById() protogo.Response {
    args := sdk.Instance.GetArgs()
    indicatorid := string(args["indicatorid"])

    if indicatorid == "" {
        return sdk.Error("indicatorid is required")
    }

    result, err := sdk.Instance.GetStateByte("ESGindicator", indicatorid)
    if err != nil {
        return sdk.Error("get state failed: " + err.Error())
    }

    if result == nil {
        return sdk.Error("record not found")
    }

    return sdk.Success(result)
}

// 合约启动入口
func main() {
    err := sandbox.Start(new(ESGTestContract))
    if err != nil {
        panic(err)
    }
}
